package com.pipayshop.exception;

import com.pipayshop.entity.vo.ResponseVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Locale;

/*全局异常处理*/
/*advice:通知*/
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})/*对哪些注解处理*/
@ResponseBody
public class GlobalExceptionHandler {

    @Autowired
    private MessageSource messageSource;

    /*
     * 处理BusinessException
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseVO handleBusinessException(BusinessException ex) {
        log.error(ex.getMessage());
        // 获取请求头中的语言信息，默认为英文
        String lang = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("lang");
        if (lang == null || lang.isEmpty()) lang = "en";  // 默认英文
        Locale locale = new Locale(lang);
        String message = messageSource.getMessage(ex.getMessage(), null, "error", locale);  // 获取国际化消息
        return ResponseVO.getFalseResponseMsg(message);
    }


}
